import Vue from "vue";
import VueRouter from "vue-router";
import store from "../store";
import Message from "@/components/utils/Message";
Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    redirect: "/home",
  },
  {
    path: "/login",
    name: "AppLogin",
    component: () => import("@/views/AppLogin.vue"),
  },
  {
    path: "/login/callback",
    name: "LoginCallback",
    component: () => import("@/views/LoginCallback.vue"),
  },
  {
    path: "/home",
    name: "AppHome",
    component: () => import("@/views/AppHome.vue"),
    redirect: "/indexView",
    children: [
      {
        path: "/indexView",
        name: "IndexView",
        component: () => import("@/components/Index/IndexView.vue"),
      },
      {
        path: "/cateView",
        name: "CateView",
        component: () => import("@/components/Category/CateView.vue"),
      },
      {
        path: "/threeCate",
        name: "ThreeCate",
        component: () => import("@/components/Category/ThreeCate.vue"),
      },
      {
        path: "/goodsDetail",
        name: "GoodsDetail",
        component: () => import("@/components/Detail/GoodsDetail.vue"),
      },
      {
        path: "/cart",
        name: "Cart",
        component: () => import("@/components/Cart/Cart.vue"),
      },
      {
        path: "/member/settle",
        name: "SettlePage",
        component: () => import("@/components/Settle/SettlePage.vue"),
      },
      {
        path: "/member/orderPay",
        name: "OrderPay",
        component: () => import("@/components/Settle/OrderPay.vue"),
      },
      {
        path: "/member/payCallback",
        name: "PayCallback",
        component: () => import("@/components/Settle/PayCallback.vue"),
      },
    ],
  },
];

const router = new VueRouter({
  routes,
  // 滚动行为
  scrollBehavior(to, from, savedPosition) {
    return { x: 0, y: 0 };
  },
});

router.beforeEach((to, from, next) => {
  if (to.fullPath.startsWith("/member")) {
    // 判断是否登录
    if (store.state.User.userInfo && store.state.User.userInfo.token) {
      next();
    } else {
      Message({ text: "请先登录", type: "error" });
      next("/login?redirectUrl=" + to.fullPath);
    }
  } else {
    next();
  }
});
export default router;
